<template>
  <div class="detail">
    <!-- 如果有数据时就渲染 -->
    <div v-if="data.length">
      <!-- Grid 宫格组件 显示选中月的支出收入结余 -->
      <van-grid :gutter="0" column-num=4 :border=false>
        <van-grid-item class="top" :text="year+'年'" />
        <van-grid-item class="top" text="月支出" />
        <van-grid-item class="top" text="月收入" />
        <van-grid-item class="top" text="月结余" />
        <van-grid-item class="bottom" @click="show=!show">
          <div class="month">{{ month+'月' }}</div>
          <div class="dir"><van-icon name="play" /></div>
        </van-grid-item>
        <van-grid-item class="bottom" :text=paySum />
        <van-grid-item class="bottom" :text=incomeSum />
        <van-grid-item class="bottom" :text=balance />
      </van-grid>
      <!-- Popup 弹出层组件 弹出年月选择 -->
      <van-popup
        v-model="show"
        position="bottom"
        :style="{height:'38%'}"
      >
        <!-- DatetimePicker 时间选择组件 选择年月 -->
        <van-datetime-picker
          v-model="currentDate"
          type="year-month"
          title="选择年月"
          :min-date="minDate"
          :max-date="maxDate"
          :formatter="formatter"
          @cancel="show=!show"
          @confirm="handleChangeDate"
        />
      </van-popup>
      <!-- 循环渲染每条数据和日期 -->
      <div v-if="dateString.length">
        <div v-for="(data,index) in dataList" :key=index>
        <!-- 时间 -->
          <p class="date">{{ data[0].date }}</p>
          <!--  -->
          <van-cell-group>
            <!-- SwipeCell 滑动单元格组件 渲染每个数据明细 -->
            <van-swipe-cell v-for="item in data" :key=item.id>
              <van-cell :border="false" >
                  <i class="iconfont" v-html="categories[0].data.filter(category=>category.title===item.category).length
                    ?
                    categories[0].data.filter(category=>category.title===item.category)[0].icon
                    :
                    categories[1].data.filter(category=>category.title===item.category)[0].icon"
                  />
                  <span class="category">{{ item.category }}</span>
                  <span class="money">{{ item.money.toFixed(2)}}</span>
              </van-cell>
              <template #right>
                <van-button
                  square
                  type="info"
                  text="修改"
                  @click="handleModifyData(item.id)"
                />
                <van-button
                  square
                  type="danger"
                  text="删除"
                  @click="handleDeleteData(item.id)"
                />
              </template>
            </van-swipe-cell>
          </van-cell-group>
        </div>
      </div>
      <!-- 没有数据时显示 -->
      <van-empty
        v-else
        class="custom-image"
        image="https://img01.yzcdn.cn/vant/custom-empty-image.png"
        description="暂无本月记录"
      />
    </div>
    <!-- 没有数据时显示 -->
    <van-empty
      v-else
      class="custom-image"
      image="https://img01.yzcdn.cn/vant/custom-empty-image.png"
      description="暂无记录"
    />
  </div>
</template>

<script>
import Vue from 'vue'
import { Toast, Dialog } from 'vant'
Vue.use(Dialog)
Vue.use(Toast)
export default {
  name: 'detail',
  created () {
    // 未登录时不渲染数据
    if (!this.$store.state.username) return
    this.categories = this.$store.state.categories
    this.date = (new Date()).toLocaleString()
    // 调用渲染函数
    this.handleRender(this.year, this.month, this.date)
  },
  data () {
    /**
     * data 用户保存的数据
     * dateString 所有数据的时间字符串
     * dataList 用户数据列表，用于渲染
     * monthPay 本月支出数据
     * monthIncome 本月收入数据
     * paySum 本月支出总和
     * incomeSum 本月收入总和
     */
    return {
      data: [],
      dateString: [],
      dataList: [],
      monthPay: [],
      monthIncome: [],
      paySum: 0,
      incomeSum: 0,
      catgories: [],
      year: (new Date()).getFullYear(),
      month: (new Date()).getMonth() + 1,
      minDate: new Date(2020, 0, 1),
      maxDate: new Date(2025, 10, 1),
      currentDate: new Date(),
      show: false,
      date: '',
    }
  },
  /**
   * balance 本月结余
   */
  computed: {
    balance () {
      return (this.incomeSum - this.paySum).toFixed(2)
    },
  },
  methods: {
    // 删除函数，点击删除时触发
    handleDeleteData (id) {
      // 跳出确认删除框
      Dialog.confirm({
        title: '删除',
        message: '确定要删除这条记录吗?',
      })
      // 点击确认时
        .then(() => {
          // 删除 state 状态数据
          this.$store.commit('handleDeleteData', {
            id,
          })
          // 调用渲染函数
          this.handleRender(this.year, this.month, this.date)
          // 提示删除成功
          Toast.success({
            message: '删除成功',
          })
        })
      // 点击取消时
        .catch(() => {
        })
    },
    // 点击修改时触发
    handleModifyData (id) {
      this.$router.push({
        name: 'modifyData',
        params: {
          id,
        },
      })
    },
    // 渲染函数，获取数据
    handleRender (year, month, str) {
      month = month > 9 ? month : '0' + month
      const min = (String(year) + month) * 100
      const max = (String(year) + month - 0 + 1) * 100
      // 初始化数据
      this.data = []
      this.dateString = []
      this.dataList = []
      this.monthPay = []
      this.monthIncome = []
      this.paySum = []
      this.incomeSum = []
      // 获取当前账号的数据
      this.data = this.$store.state.userInfo.filter(user => user.username === this.$store.state.username)[0].data
      // 将所有数据的时间字符串存放在 dateString 中
      this.data.forEach(item => {
        if (!this.dateString.includes(item.dateString) && min < item.dateString && item.dateString < max) {
          this.dateString.push(item.dateString)
        }
      })
      // 将时间字符串按照从大到小的顺序排列
      this.dateString.sort((a, b) => b - a)
      // 将时间串和时间对应起来
      this.dateString.forEach(item => {
        this.dataList.push(this.data.filter(ele => ele.dateString === item))
      })
      // 将本月收入的数据存储到 monthIncome 中
      this.monthIncome = this.data.filter(item => item.date.substring(0, 7) === str.substring(0, 7) && item.money > 0)
      // 计算出本月收入总值
      this.incomeSum = Math.abs(this.monthIncome.reduce((sum, value) => sum + value.money, 0)).toFixed(2)
      // 将本月支出的数据存储到 monthPay 中
      this.monthPay = this.data.filter(item => item.date.substring(0, 7) === str.substring(0, 7) && item.money < 0)
      // 计算出本月支出总值
      this.paySum = Math.abs(this.monthPay.reduce((sum, value) => sum + value.money, 0)).toFixed(2)
    },
    formatter (type, val) {
      if (type === 'month') {
        return `${val}月`
      } else if (type === 'year') {
        return `${val}年`
      }
      return val
    },
    handleChangeDate (value) {
      this.year = value.getFullYear()
      this.month = value.getMonth() + 1
      this.date = value.toLocaleString()
      this.show = !this.show
      this.handleRender(this.year, this.month, value.toLocaleDateString())
    },
  },
}
</script>

<style lang="less" scoped>
@font-face {
  font-family: 'iconfont';  /* Project id 3178775 */
  src: url('//at.alicdn.com/t/font_3178775_bq1p71t03t.woff2?t=1644579889842') format('woff2'),
       url('//at.alicdn.com/t/font_3178775_bq1p71t03t.woff?t=1644579889842') format('woff'),
       url('//at.alicdn.com/t/font_3178775_bq1p71t03t.ttf?t=1644579889842') format('truetype');
}
.iconfont{
    font-family:"iconfont" !important;
    font-size:16px;font-style:normal;
    -webkit-font-smoothing: antialiased;
    -webkit-text-stroke-width: 0.2px;
    -moz-osx-font-smoothing: grayscale;
}
.iconfont{
  font-size: 26px;
  color: #a0a0a0;
  vertical-align: middle;
}
.category{
  margin-left: 20px;
}
.money{
  float: right;
}
p{
  font-size: 16px;
  margin: 0;
}
/deep/.van-swipe-cell{
  line-height: 0;
}
/deep/.van-cell__value{
  overflow: visible;
}
body{
  background: #fafafa;
}
/deep/.van-grid-item__text{
  font-size: 16px;
}
.date{
  margin: 10px;
  margin-left: 16px;
}
/deep/.van-grid-item{
  height: 30px;
}
/deep/.top .van-grid-item__text{
  font-size: 14px;
}
/deep/.bottom .van-grid-item__text{
  font-size: 18px;
}
.month{
  font-size: 18px;
  color: #646566;
  line-height: 1;
}
.dir{
  transform: rotate(90deg);
  font-size: 14px;
  color:#646566;
  line-height: 1;
}
// /deep/.van-grid-item__content{
//   background-color: #1989fa;
// }
// /deep/.van-grid-item__content{
//   background-color: #f7f8fa;
// }
// /deep/.van-grid{
//   border-bottom: 50px solid #fff;
// }
</style>
